package com.example.kemgdemo.controller;

import com.example.kemgdemo.dto.req.LoginReq;
import com.example.kemgdemo.dto.req.RegisterReq;
import com.example.kemgdemo.model.Result;
import com.example.kemgdemo.service.UserService;
import com.example.kemgdemo.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 学号：1401030048
 * Created by 梁嘉伟 on 2019/7/11
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    //记录日志
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }


    @PostMapping(value = "/register")
    public Result userRegister(@Valid RegisterReq registerReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.validError(bindingResult);
        }
        if (!(registerReq.getPassword().equals(registerReq.getRepeatPassword()))) {
            return ResultUtil.matchPassword();
        }
        userService.userRegister(registerReq);
        logger.info("userRegister");
        return ResultUtil.registerSuccess();
    }

    @PostMapping(value = "/login")
    public Result userLogin(@Valid LoginReq loginReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.validError(bindingResult);
        }

        logger.info("userLogin");
        return ResultUtil.loginSuccess(userService.userLogin(loginReq));
    }
}

